package datatype;

import org.junit.Test;

import java.util.Arrays;

/**
 * @author DuJiabao
 * @create 2020-12-29 23:13
 */
public class ArrayBag<Item> {

    @Test
    public void test() {
        ArrayBag<Integer> arrayBag = new ArrayBag<Integer>();
        for (int i = 0; i < 10; i++) {
            arrayBag.add(i);
        }
        System.out.println(arrayBag.toString());
        for (int i = 0; i < 10; i++) {
            arrayBag.add(i);
        }
        System.out.println(arrayBag.toString());
    }

    private int count = 0;
    private Item[] bag = (Item[]) new Object[10];

    public ArrayBag() {
    }

    public void add(Item item) {
        if (bag.length <= count) {
            resize(2 * bag.length);
        }
        bag[count++] = item;
    }

    private void resize(int length) {
        Item[] new_bag = (Item[]) new Object[length];
        for (int i = 0; i < count; i++) {
            new_bag[i] = bag[i];
        }
        bag = new_bag;
    }

    public boolean isEmpty() {
        return count == 0;
    }

    public int size() {
        return count;
    }

    public String forEach() {
        StringBuilder result = new StringBuilder("[ ");
        for (int i = 0; i < count; i++) {
            result.append(bag[i]);
            result.append(" ");
        }
        return result + "]";
    }

    @Override
    public String toString() {
        return "ArrayBag{" +
                "count=" + count +
                ", bag=" + forEach() +
                '}';
    }
}
